package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.SetmealDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    SetmealDao setmealDao;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        if(checkgroupIds!=null&&checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.addSetmealAndCheckGroup(setmeal.getId(),checkgroupId);
            }
        }
    }

    @Override
    public PageResult findpage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page= setmealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Setmeal findById(Integer id) {

        return setmealDao.findById(id);
    }

    @Override
    public List<Integer> selectCheckgroupIdsById(int id) {
        return setmealDao.selectCheckgroupIdsById(id);
    }

    @Override
    public String findImgById(Integer id) {
        return setmealDao.findImgById(id);
    }

    @Override
    public void edit(Setmeal setmeal, Integer... checkgroupIds) {
        setmealDao.update(setmeal);
        //根据selmeal的ID删除中间表的数据
        setmealDao.deleteById(setmeal.getId());
        //根据selmeal的ID和checkgroup的ID往中间表加数据
        if(checkgroupIds!=null&&checkgroupIds.length>0) {
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.addSetmealAndCheckGroup(setmeal.getId(), checkgroupId);
            }
        }
    }

    @Override
    public void delete(int id) {
        setmealDao.deleteById(id);
        setmealDao.delete(id);
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }
}
